<template>
  <!-- 系统配置 -->
  <div class="app-container">
    <div class="none2-border3 mainbox ">
      <div class="gen_edit">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基础信息" name="first">
            <gen-basic-information ref="basicinfo" :info="info" @tabClick="tabClick"
                                   @changeInfo="changeInfo" />
          </el-tab-pane>
          <el-tab-pane label="字段映射" name="second">
            <!-- 表格 -->
            <div class="table-container table-fullscreen">
              <div class="table-opt-container">
                <el-button
                  class="filter-item"
                  @click="tabClick('first')"
                >上一步
                </el-button>
                <el-button
                  type="primary"
                  class="filter-item"
                  :loading="loading "
                  @click="tableId?updateData():saveData()"
                >保存
                </el-button>
                <el-button
                  type="primary"
                  class="filter-item"
                  :loading="genLoading "
                  @click="tableId?updateData('genCode'):saveData('genCode')"
                >保存并生成代码
                </el-button>
                <div class="flex-1" />
              </div>
              <el-form ref="columnsform" class="columnsform" :model="columnsInfo"
                       :rules="columnsRules">
                <el-table
                  ref="table"
                  v-loading="columnListLoading"
                  border
                  :data="columnsInfo.columnList"
                  highlight-current-row
                  style="width: 100%;"
                  :header-cell-style="headerCellStyle"
                >
                  <template slot="empty">
                    <p>{{ $store.getters.dataText }}</p>
                  </template>
                  <el-table-column
                    fixed="left"
                    type="index"
                    label="序号"
                    width="70"
                  />
                  <el-table-column
                    key="columnName"
                    fixed="left"
                    prop="columnName"
                    min-width="150"
                    label="字段名"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    key="columnComment"
                    prop="columnComment"
                    label="标签名称"
                    min-width="150"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item :prop="`columnList.${$index}.columnComment`" :rules="columnsRules.columnComment">
                        <el-input v-model="row.columnComment" type="text" maxlength="50" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    key="columnType"
                    prop="columnType"
                    label="字段类型"
                    width="120"
                  />
                  <el-table-column
                    key="isPk"
                    prop="isPk"
                    label="是否为主键"
                    width="105"
                  >
                    <template slot-scope="{row}">
                      <span>{{ row.isPk?'是':'否' }}</span>
                      <!-- <el-form-item :prop="`columnList.${$index}.isPk`">
                        <el-checkbox v-model="scope.row.isPk" />
                      </el-form-item> -->
                    </template>
                  </el-table-column>
                  <!-- <el-table-column
                    key="tagName"
                    prop="tagName"
                    label="标签名称"
                    min-width="150"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item :prop="`columnList.${$index}.tagName`">
                        <el-input v-model.trim="row.tagName" type="text" maxlength="50" />
                      </el-form-item>
                    </template>
                  </el-table-column> -->
                  <el-table-column
                    key="javaType"
                    prop="javaType"
                    label="Java类型"
                    width="150"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item :prop="`columnList.${$index}.javaType`">
                        <el-select v-model="row.javaType">
                          <el-option label="Long" value="Long" />
                          <el-option label="String" value="String" />
                          <el-option label="Integer" value="Integer" />
                          <el-option label="Double" value="Double" />
                          <el-option label="BigDecimal" value="BigDecimal" />
                          <el-option label="Date" value="Date" />
                          <el-option label="Boolean" value="Boolean" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    key="javaField"
                    prop="javaField"
                    label="Java属性"
                    width="150"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item :prop="`columnList.${$index}.javaField`">
                        <el-input v-model.trim="row.javaField" type="text" maxlength="50" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    key="isShow"
                    prop="isShow"
                    label="列表是否展示"
                    width="118"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item :prop="`columnList.${$index}.isShow`">
                        <el-checkbox v-model="row.isShow" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    key="isQuery"
                    prop="isQuery"
                    label="是否为查询条件"
                    width="135"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item :prop="`columnList.${$index}.isQuery`">
                        <el-checkbox v-model="row.isQuery" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    key="queryType"
                    prop="queryType"
                    label="查询方式"
                    width="150"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item v-if="row.isQuery == false" key="noProp">
                        <el-select v-model="row.queryType" :disabled="row.isQuery == false">
                          <el-option label="=" value="EQ" />
                          <el-option label="!=" value="NE" />
                          <el-option label=">" value="GT" />
                          <el-option label=">=" value="GTE" />
                          <el-option label="<" value="LT" />
                          <el-option label="<=" value="LTE" />
                          <el-option label="LIKE" value="LIKE" />
                          <el-option label="BETWEEN" value="BETWEEN" />
                        </el-select>
                      </el-form-item>
                      <el-form-item v-else key="hasProp" :prop="`columnList.${$index}.queryType`"
                                    :rules="columnsRules.queryType">
                        <el-select v-model="row.queryType" :disabled="row.isQuery == false">
                          <el-option label="=" value="EQ" />
                          <el-option label="!=" value="NE" />
                          <el-option label=">" value="GT" />
                          <el-option label=">=" value="GTE" />
                          <el-option label="<" value="LT" />
                          <el-option label="<=" value="LTE" />
                          <el-option label="LIKE" value="LIKE" />
                          <el-option label="BETWEEN" value="BETWEEN" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    key="formIsShow"
                    prop="formIsShow"
                    label="表单是否展示"
                    width="118"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item :prop="`columnList.${$index}.formIsShow`">
                        <el-checkbox v-model="row.formIsShow" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    key="htmlType"
                    prop="htmlType"
                    label="表单类型"
                    width="150"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item :prop="`columnList.${$index}.htmlType`">
                        <el-select v-model="row.htmlType">
                          <el-option label="文本框" value="input" />
                          <el-option label="文本域" value="textarea" />
                          <el-option label="下拉框" value="select" />
                          <el-option label="单选框" value="radio" />
                          <el-option label="复选框" value="checkbox" />
                          <el-option label="日期控件" value="datetime" />
                          <el-option label="图片上传" value="imageUpload" />
                          <el-option label="文件上传" value="fileUpload" />
                          <el-option label="富文本控件" value="editor" />
                        </el-select>
                      </el-form-item>

                    </template>
                  </el-table-column>
                  <el-table-column
                    key="isRequired"
                    prop="isRequired"
                    label="表单是否必填"
                    width="118"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item :prop="`columnList.${$index}.isRequired`">
                        <el-checkbox v-model="row.isRequired" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    key="dictTypeCode"
                    prop="dictTypeCode"
                    label="数据字典"
                    width="150"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item :prop="`columnList.${$index}.dictTypeCode`">
                        <el-select v-model="row.dictTypeCode" :disabled="row.htmlType!=='radio'&&row.htmlType!=='checkbox'&&row.htmlType!=='select'" clearable
                                   filterable placeholder="请选择">
                          <el-option
                            v-for="dict in dictTypeList"
                            :key="dict.dictTypeCode"
                            :label="dict.dictTypeName"
                            :value="dict.dictTypeCode"
                          >
                            <span style="float: left">{{ dict.dictTypeName }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictTypeCode }}</span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    key="checkMode"
                    prop="checkMode"
                    label="校验"
                    width="150"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item :prop="`columnList.${$index}.checkMode`">
                        <el-select v-model="row.checkMode" placeholder="请选择">
                          <el-option
                            v-for="item in ruleList"
                            :key="item.value"
                            :label="item.type"
                            :value="item.value"
                          />
                        </el-select>
                        <el-input v-if="row.checkMode===1" v-model.trim="row.checkExpression" placeholder="自定义表达式"
                                  type="text" maxlength="100" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>

            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

    </div>
  </div>
</template>
<script>
import { saveAs } from 'file-saver'
import codeGenerationApi, { getColumnsList, addGen, updateGen, detailGen } from '@/framework/api/codeGeneration'
// import { page } from '@/framework/api/dictType'
import dictTypeApi from '@/framework/api/dictType'

import genBasicInformation from './components/genBasicInformation.vue'

export default {
  components: {
    genBasicInformation
  },
  data() {
    return {
      columnsRules: {
        columnComment: [
          // { required: true, validator: validatePassword, trigger: ['blur', 'change'] }
          { required: true, message: '请输入字段说明', trigger: 'blur' }

        ],
        // isPk: [
        //   { required: false, message: '请选择是否为主键', trigger: 'blur' }
        // ],
        // tagName: [
        //   { required: false, message: '请输入标签名称', trigger: 'blur' }
        // ],
        javaType: [
          { required: true, message: '请选择Java类型', trigger: 'blur' }
        ],
        javaField: [
          { required: true, message: '请输入Java属性', trigger: 'blur' }
        ],
        // isShow: [
        //   { required: false, message: '请选择是否展示', trigger: 'blur' }
        // ],
        // isQuery: [
        //   { required: false, message: '请选择是否为查询条件', trigger: 'blur' }
        // ]
        queryType: [
          { required: true, message: '请选择查询方式', trigger: 'blur' }
        ]
        // isRequired: [
        //   { required: false, message: '请选择是否必填', trigger: 'blur' }
        // ]
      },
      dataRourceList: [],
      activeName: 'first',
      columnListLoading: false,
      headerCellStyle: {
        backgroundColor: '#f2f2f2'
      },
      loading: false,
      genLoading: false,
      /**
 * 校验方式
 * 1自定义校验
 * 2名称
 * 3编码
 * 4排序
 * 5手机号
 * 6邮箱
 */
      ruleList: [
        { type: '自定义校验', value: 1 },
        { type: '名称', value: 2 },
        { type: '编码', value: 3 },
        { type: '排序', value: 4 },
        { type: '手机号', value: 5 },
        { type: '邮箱', value: 6 }
      ],
      // 表基础信息
      info: {
        tableName: '',
        tableComment: '',
        moduleName: '',
        author: ''
      },
      dbId: '',
      columnsInfo: {
        columnList: []
      },
      dictTypeList: [],
      tableId: ''
    }
  },
  created() {
  },
  mounted() {
    this.getConfigDictTypeList()
    if (this.$route.query.tableId) {
      this.tableId = this.$route.query.tableId
      this.getDetailGen(this.tableId)
    }
    // 修改-查询详情
  },
  methods: {
    changeInfo(info) {
      this.info = info
    },
    // 编辑 获取数据
    getDetailGen(tableId) {
      detailGen({ tableId }).then((res) => {
        this.columnsInfo = res.data
        const { columnList, ...info } = this.columnsInfo
        this.columnsInfo.columnList = columnList
        this.info = info
      })
    },
    // 编辑修改后保存
    updateData(type) {
      this.$refs['columnsform'].validate((valid) => {
        if (valid) {
          if (type === 'genCode') {
            this.genLoading = true
          } else {
            this.loading = true
          }
          this.columnsInfo = { ...this.columnsInfo, ...this.$refs.basicinfo.info }
          updateGen(this.columnsInfo).then((res) => {
            if (res.success) {
              this.$dtMessage({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
              if (type === 'genCode') {
                this.codeGenerate(res.data.tableId)
                this.genLoading = false
              } else {
                this.loading = false
              }
              this.$router.push('/devTools/codeGeneration')
            }
          })
        } else {
          this.genLoading = false
          this.loading = false
          return false
        }
      })
    },

    // 获取字典类型列表
    getConfigDictTypeList() {
      dictTypeApi.page({ pageNo: 1, pageSize: 1000000 }).then((res) => {
        this.dictTypeList = res.data.rows
      })
    },
    handleClick(tab, event) {
    },
    tabClick(step) {
      this.activeName = step
      if (step === 'second' && !this.$route.query.tableId) {
        this.getColumnsInfo()
      }
    },
    // 新增获取字段映射的列表
    getColumnsInfo() {
      const query = {
        dbId: this.$refs.basicinfo.info.dbId,
        tableName: this.$refs.basicinfo.info.tableName,
        schemaName: this.$refs.basicinfo.info.tableSchema
      }
      getColumnsList(query).then((res) => {
        this.columnsInfo.columnList = res.data
      })
    },
    // 新增 保存
    saveData(type) {
      this.$refs['columnsform'].validate((valid) => {
        if (valid) {
          this.loading = true
          // this.$emit('tabClick', 'second')
          // this.columnsInfo.info = this.$refs.basicinfo.info
          this.columnsInfo = { ...this.columnsInfo, ...this.$refs.basicinfo.info }
          addGen(this.columnsInfo).then((res) => {
            if (res.success) {
              this.$dtMessage({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
              this.$router.push('/devTools/codeGeneration')
              this.loading = false
              return res.data.tableId
            }
          }).then((res) => {
            if (type === 'genCode') {
              this.codeGenerate(res)
            }
          })
        } else {
          this.loading = false
          return false
        }
      })
    },
    codeGenerate(tableId) {
      codeGenerationApi.genCode({ tableId }).then(async (res) => {
        const blob = new Blob([res.data])
        saveAs(blob, 'genCode.zip')
      })
    }

  }
}
</script>
<style lang="scss" scoped>
.gen_edit{
    height: 100%;
    flex: 1;
    background: #fff;
    padding: 0 20px 20px;
    border-radius: 4px;
    box-shadow: 0px 4px 8px 2px rgb(0 0 0 / 4%), 0px 2px 6px 0px rgb(0 0 0 / 6%), 0px 0px 4px 0px rgb(0 0 0 / 8%);
}
.columnsform .el-form-item{
  margin-bottom:0!important;
}
</style>
